//
//  VDViewController.m
//  Gunz
//
//  Created by Joggy on 16/8/24.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "VDViewController.h"
#import "YGVideoPickerController.h"

@interface VDViewController ()<YGVideoPickerControllerDelegate> {
    
    
    
}

@end

@implementation VDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareForNav];
    [self prepareForLayout];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)prepareForNav {
    [super prepareForNav];
    self.title = @"视频录制";
    //导航左按键
    UIImage *image = [UIImage imageNamed:@"all_back"];
    UIButton *leftBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBarButton.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    leftBarButton.layer.position = CGPointMake(22, 22);
    [leftBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [leftBarButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarButton];
}

- (void)prepareForLayout {
    [super prepareForLayout];
    UIButton *tapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    tapButton.frame = CGRectMake(0, 0, 120, 66);
    tapButton.center = CGPointMake(screenWidth/2, screenHeight*2/3);
    tapButton.layer.cornerRadius = 6;
    [tapButton setTitle:@"点击录制" forState:UIControlStateNormal];
    [tapButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    tapButton.backgroundColor = CUSTOM_GREEN;
    [tapButton addTarget:self action:@selector(recordingView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tapButton];
}

- (void)recordingView
{
    YGVideoPickerController *controller = [[YGVideoPickerController alloc]init];
    controller.maxVideoTime = 90;
    controller.minVideoTime = 1;
    controller.delegate = self;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:controller];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)back {
    [self dismissViewControllerAnimated:true completion:nil];
}

-(void)YGVideoPickerController:(YGVideoPickerController *)controller didPressYesButtonWithMP4FilePath:(NSString *)path thumbImage:(UIImage *)thumbImage
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入文件名" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"文件名";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields[0];
        NSString *superPath = [NSString stringWithFormat:@"%@/%@", documentBasePath, GZUserVideoPath];
        NSFileManager *manager = [NSFileManager defaultManager];
        if(![manager fileExistsAtPath:superPath]) {
            [manager createDirectoryAtPath:superPath withIntermediateDirectories:true attributes:nil error:nil];
        }
        
        if([textField.text isEqualToString:@""]) {
            textField.text = [GZConst getCurrentDateFormate];
        }
        
        NSString *savePath = [NSString stringWithFormat:@"%@/%@/%@.mp4", documentBasePath, GZUserVideoPath, textField.text];
        AVURLAsset *avAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:path]];
        NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
        if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality])
        {
            AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
            exportSession.outputURL = [NSURL fileURLWithPath:savePath];
            exportSession.outputFileType = AVFileTypeMPEG4;
            exportSession.shouldOptimizeForNetworkUse = YES;
            [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
             {
                 switch (exportSession.status) {
                         
                     case AVAssetExportSessionStatusUnknown:
                         
                         NSLog(@"AVAssetExportSessionStatusUnknown");
                         
                         break;
                         
                     case AVAssetExportSessionStatusWaiting:
                         
                         NSLog(@"AVAssetExportSessionStatusWaiting");
                         
                         break;
                         
                     case AVAssetExportSessionStatusExporting:
                         
                         NSLog(@"AVAssetExportSessionStatusExporting");
                         
                         break;
                         
                     case AVAssetExportSessionStatusCompleted:
                     {
                         NSLog(@"AVAssetExportSessionStatusCompleted");
                         
                         //跳回主线程
                         //                     [self performSelectorOnMainThread:@selector(completeConventWithPathString:) withObject:MP4PathString waitUntilDone:NO];
                     }
                         break;
                         
                     case AVAssetExportSessionStatusFailed:
                         
                         NSLog(@"AVAssetExportSessionStatusFailed");
                         
                         break;
                         
                     case AVAssetExportSessionStatusCancelled:
                         
                         NSLog(@"AVAssetExportSessionStatusCancelled");
                         
                         break;
                 }
                 
             }];
        }

    }]];
    [self presentViewController:alert animated:true completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
